<?php

class NewsController extends Controller
{
	private $_model;
	
	public function actionIndex()
	{
		$criteria = new CDbCriteria(array(
				'condition' => 'status=1',
				'order' => 'create_time DESC',
				//'with'=>'commentCount',
		));
		/*if(isset($_GET['tag']))
		 $criteria->addSearchCondition('tags',$_GET['tag']);*/
		
		$dataProvider = new CActiveDataProvider('News', array(
				'pagination' => array(
						'pageSize' => Yii::app()->params['postsPerPage'],
				),
				'criteria' => $criteria,
		));
		
		
		$this->render('index',array('dataProvider'=>$dataProvider));
	}

	public function actionView()
	{
		$model = $this->loadModel();
		$comment = $this->newComment($model);
		
		$this->render('view',array('model'=>$model,'comment'=>$comment));
	}
	
	public function loadModel()
	{
		if ($this->_model === null) 
		{
			if (isset($_GET['id'])) 
			{
				$condition = '';
				$this->_model = News::model()->findByPk($_GET['id'], $condition);
			}
			
			if ($this->_model === null)
				throw new CHttpException(404, 'The requested page does not exist.');
		}
		
		return $this->_model;
	}
	/**
	 * @param $news News
	 * @return Comments
	 */
	protected function newComment($news)
	{
		$comment = new Comments;
		if (!Yii::app()->user->isGuest) {
			$comment->user_id = (int)Yii::app()->user->id;

		}
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'comments-form') {
			echo CActiveForm::validate($comment);
			Yii::app()->end();
		}
		if (isset($_POST['Comments'])) {
			$comment->attributes = $_POST['Comments'];
			if ($news->addComment($comment)) {
				Yii::app()->user->setFlash('commentSubmitted', 'Cảm ơn bạn đã bình luận.');
				$this->refresh();
			}
		}
		return $comment;
	}
}